package database

import (
	"gitee.com/zhucheer/orange/cfg"
	"gitee.com/zhucheer/orange/logger"
	"github.com/zhuCheer/pool"
)

type DataBase interface {
	RegisterAll()
	Register(string)
	insertPool(string, pool.Pool)
	getDB(string) (interface{}, func(), error)
	putDB(string, interface{}) error
}

type dbChan struct {
	dbType string
	name   string
	conn   interface{}
}

// PutConn 将连接放回连接池方法
func PutConn(put func()) {
	if put == nil {
		return
	}
	put()
	return
}

// PullChanDB 持续监听将chan中的连接异步放回连接池
func PullChanDB() {
	if mysqlConn.count+redisConn.count == 0 {
		return
	}

	for {
		if mysqlConn.connList.Len() == 0 {
			break
		}
		conn := mysqlConn.connList.LPop()
		if conn == nil {
			break
		}

		dbConn := conn.(dbChan)
		err := mysqlConn.putDB(dbConn.name, dbConn.conn)
		if err != nil {
			logger.Error("mysql conn put back err:%v", err)
		}
	}

	for {
		if redisConn.connList.Len() == 0 {
			break
		}
		conn := redisConn.connList.LPop()
		if conn == nil {
			break
		}

		dbConn := conn.(dbChan)
		err := redisConn.putDB(dbConn.name, dbConn.conn)
		if err != nil {
			logger.Error("redis conn put back err:%v", err)
		}
	}
}

func getDBIntConfig(dbtype, name, key string) int {
	exists := cfg.Config.Exists("database." + dbtype + "." + name + "." + key)
	if exists == false {
		return cfg.Config.GetInt("database." + key)
	}
	return cfg.Config.GetInt("database." + dbtype + "." + name + "." + key)
}

func getBoolConfig(dbtype, name, key string) bool {
	exists := cfg.Config.Exists("database." + dbtype + "." + name + "." + key)
	if exists == false {
		return cfg.Config.GetBool("database." + key)
	}
	return cfg.Config.GetBool("database." + dbtype + "." + name + "." + key)
}
